package com.gsmr.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.gsmr.entity.GPRSInfo;
import com.gsmr.entity.PageBean;
import com.gsmr.service.GPRSInfoService;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.PropertityUtil;
import com.gsmr.util.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/gprs_info")
public class GPRSInfoController {

	@Resource
	private GPRSInfoService GPRSInfoService;

	/**
	 * 分页条件查询GPRSInfo
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows, 
			 HttpServletResponse response) throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "gprsinfo");
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<GPRSInfo> bsInfoList = GPRSInfoService.find(map);
		Long total = GPRSInfoService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(bsInfoList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
	}


	/**
	 * 添加或者修GPRS_info
	 * @param flag 1 添加 2修改
	 */
	@RequestMapping("/save")
	public void save(GPRSInfo bsInfo, HttpServletResponse response, Integer flag) throws Exception {
		int resultTotal = 0; // 操作的记录条数
		Map<String, Object> map = new HashMap<>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "gprsinfo");
		map.put("id", bsInfo.getId());
		map.put("voiceCard", bsInfo.getVoiceCard());
		map.put("dataCardMSISDN", bsInfo.getDataCardMSISDN());
		map.put("dataCardIMSI", bsInfo.getDataCardIMSI());
		map.put("EngineNo", bsInfo.getEngineNo());
		map.put("ipAddress", bsInfo.getIpAddress());

		if (flag == 1) {
			resultTotal = GPRSInfoService.add(map);
		} else {
			resultTotal = GPRSInfoService.update(map);
		}
		JSONObject result = new JSONObject();
		if (resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
	}

	/**
	 * 删除GPRS_info
	 */
	@RequestMapping("/delete")
	public void delete(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception {
		String[] idsStr = ids.split(",");
		Map<String, Object> map = new HashMap<>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "gprsinfo");

		JSONObject result = new JSONObject();
		
		for (int i = 0; i < idsStr.length; i++) {
			map.put("id", idsStr[i]);
			//System.out.println(map);
			try {
				GPRSInfoService.delete(map);
			} catch (Exception e) {
				e.printStackTrace();
				result.put("success", false);
				ResponseUtil.write(response, result);
				return;
			}
		}
		result.put("success", true);
		ResponseUtil.write(response, result);
	}


	/**
	 * 导出GPRS_info
	 */
	@RequestMapping("/export")
	public void export(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception {
		
		Map<String, Object> map = new HashMap<>();
		Workbook wb = new HSSFWorkbook();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "gprsinfo");
		
		String headers[] = {"Id", "voiceCard", "dataCardMSISDN", "dataCardIMSI", "IP地址", "机车号"};
		
		if (ids != null && !ids.equals("null") && ids.length() > 0) {
			map.put("ids", Arrays.asList(ids.split(",")));
		} else {
			map.put("ids", null);
		}
		
		List<GPRSInfo> list = GPRSInfoService.findByIds(map);
		//System.out.println(list);
		try {
			ExcelUtil.fillExcelDataGPRSInfo(list, wb, headers);
			ResponseUtil.export(response, wb, "导出GPRSInfo" + FormatDate.formatDate() + ".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * GPRSInfo上传
	 */
	@RequestMapping("/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response, Integer uploadFlag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "gprsinfo");
		map.put("id", "0 OR 1=1");
		if (uploadFlag == 2) {
			GPRSInfoService.delete(map);
		}
		
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					//String path = file.getOriginalFilename();
					String path = "已导入" + new Date().getTime() + file.getOriginalFilename();
					// 上传
					File newFile = new File(path);
					file.transferTo(newFile);
					// 写数据进数据库
					POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(newFile));
					newFile.delete();
					HSSFWorkbook wb = new HSSFWorkbook(fs);
					HSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页
					JSONObject result = new JSONObject();
					try {
						if (hssfSheet != null) {
							for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
								HSSFRow hssfRow = hssfSheet.getRow(rowNum);
								if (hssfRow == null) {
									continue;
								}
								
								String id = ExcelUtil.formatCell(hssfRow.getCell(0));
								
								if (id.length() < 1 || existId(id, null)) {
									System.out.println("Id: " + id + "已存在，跳过该行。");
									continue;
								}
								map.put("id", ExcelUtil.formatCell(hssfRow.getCell(0)));
								map.put("voiceCard", ExcelUtil.formatCell(hssfRow.getCell(1)));
								map.put("dataCardMSISDN", ExcelUtil.formatCell(hssfRow.getCell(2)));
								map.put("dataCardIMSI", ExcelUtil.formatCell(hssfRow.getCell(3)));
								map.put("EngineNo", ExcelUtil.formatCell(hssfRow.getCell(5)));
								map.put("ipAddress", ExcelUtil.formatCell(hssfRow.getCell(4)));
								
								GPRSInfoService.add(map);
							}
						}
						result.put("success", true);
					} catch (Exception e) {
						result.put("success", false);
						e.printStackTrace();
					}
					ResponseUtil.write(response, result);
				}
			}
		}
	}

	
	/**
	 * 判断是否存在指定用户名
	 */
	@RequestMapping("/existId")
	public Boolean existId(String id, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		Map<String, Object> map = new HashMap<>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "gprsinfo");
		map.put("id", id);
		
		boolean hasDuplicate = false;
		if (GPRSInfoService.findById(map) == null) {
			result.put("exist", false);
		} else {
			result.put("exist", true);
			hasDuplicate = true;
		}
		if (response != null) {
			ResponseUtil.write(response, result);
			return null;
		}
		return hasDuplicate;
	}
}